package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"tik-res-man/chone"
	"tik-res-man/modler"
	"tik-res-man/pkg"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	redis_key := "login" + username
	errCont, _ := chone.Rdb.Get(chone.Ctx, redis_key).Int()
	if errCont >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次紧张登录",
		})
		return
	}
	var user modler.User
	err := modler.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		chone.Rdb.Incr(chone.Ctx, redis_key)
		if errCont == 2 {
			chone.Rdb.Set(chone.Ctx, redis_key, "3", time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次封禁2小时",
			})
			return
		}
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "登录成功",
			"data": user,
		})
		return
	}

}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size

	var video []modler.Video
	redis_key := "list" + strconv.Itoa(page)
	result, _ := chone.Rdb.Get(chone.Ctx, redis_key).Result()
	if result == "" {
		modler.DB.Offset(offset).Limit(size).Debug().Find(&video)
		marshal, _ := json.Marshal(video)
		chone.Rdb.Set(chone.Ctx, redis_key, marshal, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &video)
	}

	var Count int64
	modler.DB.Model(modler.Video{}).Count(&Count)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  video,
		"count": Count,
	})
}

func ListAdd(c *gin.Context) {
	id := c.Query("id")
	var video modler.Video
	redis_key := "listAdd" + id
	result, _ := chone.Rdb.Get(chone.Ctx, redis_key).Result()
	if result == "" {
		modler.DB.Where("id=?", id).First(&video)
		marshal, _ := json.Marshal(video)
		chone.Rdb.Set(chone.Ctx, redis_key, marshal, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &video)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": video,
	})
}

func Like(c *gin.Context) {
	title := c.PostForm("title")
	Content := c.PostForm("content")
	img := c.PostForm("img")
	LikeCount, _ := strconv.Atoi(c.PostForm("likecount"))
	video := modler.Video{

		Title:     title,
		Content:   Content,
		Img:       img,
		LikeCount: LikeCount,
	}
	tx := modler.DB.Begin()
	err := tx.Create(&video).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "点赞失败",
		})
		return
	} else {
		tx.Commit()
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "点赞成功",
		})
		return
	}
}
